package com.century.sjt.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.Constant;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.util.FileUtil;
import com.century.sjt.util.TipUtil;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.century.sjt.EMChat.adapter.EaseContactAdapter;
import com.century.sjt.EMChat.domain.EaseUser;
import com.century.sjt.EMChat.ui.EaseBaseActivity;
import com.century.sjt.EMChat.widget.EaseSidebar;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class ShareFriendActivity extends EaseBaseActivity {

    private ListView listView;
    private EaseSidebar sidebar;
    protected EaseContactAdapter contactAdapter;
    private List<EaseUser> contactList;
    private String imageUrl;
    private String picId;

    private Handler mHandler;
    private RequestQueue mQueue;
    private EditText queryEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_choose_afriend_activity);
        mQueue = Volley.newRequestQueue(ShareFriendActivity.this);
        imageUrl = getIntent().getStringExtra("imageUrl");
//        picId = imageUrl.substring(imageUrl.length() - 22, imageUrl.length() - 4);//获取图片Id的方式(旧)
        String[] strImageUrl = imageUrl.split("/");//获取图片Id的方式
        picId = strImageUrl[strImageUrl.length-1];
        TipUtil.log("picId", picId, 1);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        TipUtil.showToast(getResources().getString(R.string.error_sending_success), ShareFriendActivity.this, 1);
                        finish();
                        break;
                    case 2:
                        TipUtil.showToast(getResources().getString(R.string.error_sending_fail), ShareFriendActivity.this, 1);
                        break;
                }
            }
        };

        listView = (ListView) findViewById(R.id.list);
        sidebar = (EaseSidebar) findViewById(R.id.sidebar);
        sidebar.setListView(listView);
        queryEditText = (EditText) findViewById(R.id.query);
        contactList = new ArrayList<EaseUser>();
        // 获取设置contactlist
        getContactList();
        // 设置adapter
        contactAdapter = new EaseContactAdapter(this, R.layout.ease_row_contact, contactList);
        listView.setAdapter(contactAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onListItemClick(position);
            }
        });
        queryEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (queryEditText.getText().length() == 0 || "".equals(queryEditText.getText().toString())) {
                    getContactList();
                } else {
                    seabarUser(queryEditText.getText().toString().trim());
                }
                contactAdapter.notifyDataSetChanged();
            }

        });


    }

    protected void onListItemClick(int position) {
        saveImage(picId, imageUrl, mQueue, contactAdapter.getItem(position).getUsername());

    }

    /**
     * 保存图片
     * @param picId
     * @param picUrl
     * @param mQueue
     * @param username
     */
    private void saveImage(final String picId, final String picUrl, RequestQueue mQueue, final String username) {
        FileUtil.createImageDir();
        File file = new File(com.century.sjt.util.Constant.CAMERA_PICTURE_PATH, picId);
        if (!file.exists()) {//文件不存在，下载下来
            ImageRequest imageRequest = new ImageRequest(picUrl, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    FileUtil.saveImg(bitmap, picId);                //保存图片
                    sendImage(com.century.sjt.util.Constant.CAMERA_PICTURE_PATH + picId, username);
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    TipUtil.showToast(getResources().getString(R.string.error_download_picture_wrong), ShareFriendActivity.this, 1);
                    TipUtil.log("图片下载失败", volleyError.toString(), 1);
                }
            });
            mQueue.add(imageRequest);
        } else {
            sendImage(com.century.sjt.util.Constant.CAMERA_PICTURE_PATH + picId, username);
        }
    }

    /**
     * 发送图片
     * @param imageFilePath
     * @param username
     */
    private void sendImage(String imageFilePath, String username) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
//如果是群聊，设置chattype，默认是单聊
//    message.setChatType(ChatType.GroupChat);

        ImageMessageBody body = new ImageMessageBody(new File(imageFilePath));
// 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
// body.setSendOriginalImage(true);
        message.addBody(body);
        message.setReceipt(username);
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.log("发送图片", "发送成功", 1);
            }

            @Override
            public void onError(int i, String s) {
                TipUtil.closeProgressDialog();
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
                TipUtil.log(i + "发送失败", s, 1);
            }

            @Override
            public void onProgress(int i, String s) {
                TipUtil.openProgressDialog(com.century.sjt.util.Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), ShareFriendActivity.this);
            }
        });
    }

    public void back(View view) {
        finish();
    }

    private void getContactList() {
        contactList.clear();
        Map<String, EaseUser> users = SjtHelper.getInstance().getContactList();
        Iterator<Map.Entry<String, EaseUser>> iterator = users.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, EaseUser> entry = iterator.next();
            if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.GROUP_USERNAME) && !entry.getKey().equals(Constant.CHAT_ROOM) && !entry.getKey().equals(Constant.CHAT_ROBOT))
                if (!entry.getValue().getUsername().equals("00000000")) {
                    if ("0".equals(entry.getValue().getIsShop())) {
                        contactList.add(entry.getValue());
                    }
                }
        }
        // 排序
        Collections.sort(contactList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();

    }
    /**
     * list 模糊搜索好友
     */
    public void seabarUser(final String srcName){
        for(int i=0;i<contactList.size();i++ ){
            if(((EaseUser)(contactList.get(i))).getNick().indexOf(srcName)<=-1){
                contactList.remove(i);
            }
        }
        // 排序
        Collections.sort(contactList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });

    }
}



